#include<iostream>
using namespace std;
#include<vector>
class Solution {
public:
    int maxSumDivThree(vector<int>& nums) {
        int sum = 0;
        for (auto& e : nums)
            sum += e;
        int one1 = INT_MAX, one2 = INT_MAX, tow1 = INT_MAX, tow2 = INT_MAX;
        for (auto& e : nums) {
            if (e % 3 == 1) {
                if (one1 == INT_MAX)
                    one1 = e;
                else {
                    if (e < one1) {
                        one2 = one1;
                        one1 = e;
                    }
                    else {
                        one2 = min(one2, e);
                    }
                }
            }
            else if (e % 3 == 2) {
                if (tow1 == INT_MAX)
                    tow1 = e;
                else {
                    if (e < tow1) {
                        tow2 = tow1;
                        tow1 = e;
                    }
                    else {
                        tow2 = min(tow2, e);
                    }
                }
            }
        }
        if (sum % 3 == 0)
            return sum;
        if (sum % 3 == 1) {
            int one = one1;
            int two = INT_MAX;
            if (tow2 != INT_MAX)
                two = tow1 + tow2;
            return max(0, max(sum - one, sum - two));
        }
        int two = tow1;
        int one= INT_MAX;
        if (one2 != INT_MAX)
            one = one1 + one2;
        return max(0, max(sum - one, sum - two));
    }
};